import React, { useState, useEffect } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import App from './App';
import _ from 'lodash';
import { menuConfig } from '@/config/menuConfig';
import { routerPrefix } from '@/config/config';
import menuConfigMap from '@/config/menuConfigMap';

const Router = () => {
  const [menu_config, setMenu_config] = useState(menuConfig);
  useEffect(() => {
    // 动态路由
    setTimeout(() => {
      const newMenuConfig = [...menu_config];
      newMenuConfig.push({
        id: '#2',
        name: '我的相册',
        path: 'album',
        component: menuConfigMap.Album,
      });
      setMenu_config(newMenuConfig);
    }, 3000);
  }, []);

  const renderRoute = (data) => {
    return _.map(data, (item, key) => {
      if (_.isArray(item.children) && !_.isEmpty(item.children)) {
        return (
          <Route
            key={item.id}
            path={item.path}
            element={<item.component />}
            {...item.componentProps}
          >
            {renderRoute(item.children)}
          </Route>
        );
      }
      if (_.isArray(item.path) && !_.isEmpty(item.path)) {
        return renderRoute(item.path);
      }

      return (
        <Route
          key={item.id}
          path={item.path}
          element={<item.component />}
          {...item.componentProps}
        ></Route>
      );
    });
  };
  return (
    <>
      <Routes>
        <Route path="/" element={<Navigate to={routerPrefix} />}></Route>
        <Route path={routerPrefix} element={<App menuConfig={menu_config} />}>
          {renderRoute(menu_config)}
        </Route>
        <Route path="*" element={<h1>404</h1>}></Route>
      </Routes>
    </>
  );
};

export default Router;
